package com.example.yc.Service;

import com.example.yc.mapper.TestMapper;
import com.example.yc.pojo.Json;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Time;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@CacheConfig
public class TestService {
    @Resource
    private TestMapper testMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 获取列表
     * 如果缓存存在，从缓存中获取信息
     * 如果缓存不存在，从DB中获取信息，然后插入缓存
     * @param name
     * @return
     */
    public String findTestList(String name){
        String key = "test_"+name;
        ValueOperations<String,String> operations = redisTemplate.opsForValue();
        //缓存是否存在
        //从缓存中获取
        if(redisTemplate.hasKey(key)){
            String lh = operations.get(key);
            System.out.println(">>>>>>>>>>>从缓存中获取"+lh.toString());
            return lh;
        }

        //从DB中获取
        List<HashMap<String,String>> lhdb = testMapper.getAllTest();

        //插入到缓存
        operations.set(key,lhdb.toString(),10,TimeUnit.SECONDS);
        System.out.println(">>>>>>>>>>>>从DB中获取"+lhdb.toString());

        return lhdb.toString();
    }
}
